﻿using System.Collections;
using System.ComponentModel;

namespace Koala.Pro.Common
{
    public class EnumHelper
    {
        public static T GetInstance<T>(string member)
        {
            return ConvertHelper.ConvertTo<T>(Enum.Parse(typeof(T), member, ignoreCase: true));
        }

        public static Dictionary<string, object> GetMemberKeyValue<T>()
        {
            Dictionary<string, object> dictionary = new Dictionary<string, object>();
            string[] memberNames = GetMemberNames<T>();
            foreach (string text in memberNames)
            {
                dictionary.Add(text, GetMemberValue<T>(text));
            }
            return dictionary;
        }

        public static string[] GetMemberNames<T>()
        {
            return Enum.GetNames(typeof(T));
        }

        public static string GetMemberName<T>(object member)
        {
            Type underlyingType = GetUnderlyingType(typeof(T));
            object value = ConvertHelper.ConvertTo(member, underlyingType);
            return Enum.GetName(typeof(T), value);
        }

        public static Array GetMemberValues<T>()
        {
            return Enum.GetValues(typeof(T));
        }

        public static object GetMemberValue<T>(string memberName)
        {
            Type underlyingType = GetUnderlyingType(typeof(T));
            return ConvertHelper.ConvertTo(GetInstance<T>(memberName), underlyingType);
        }

        public static Type GetUnderlyingType(Type enumType)
        {
            return Enum.GetUnderlyingType(enumType);
        }

        public static bool IsDefined<T>(string member)
        {
            return Enum.IsDefined(typeof(T), member);
        }

        public static string GetDescription(Type t, object v)
        {
            try
            {
                DescriptionAttribute[] array = (DescriptionAttribute[])t.GetField(GetName(t, v)).GetCustomAttributes(typeof(DescriptionAttribute), inherit: false);
                return (array.Length != 0) ? array[0].Description : GetName(t, v);
            }
            catch
            {
                return "UNKNOWN";
            }
        }

        private static string GetName(Type t, object v)
        {
            try
            {
                return Enum.GetName(t, v);
            }
            catch
            {
                return "UNKNOWN";
            }
        }

        public static SortedList GetStatus(Type t)
        {
            SortedList sortedList = new SortedList();
            Array values = Enum.GetValues(t);
            for (int i = 0; i < values.Length; i++)
            {
                string value = values.GetValue(i).ToString();
                int num = (int)Enum.Parse(t, value);
                string description = GetDescription(t, num);
                sortedList.Add(num, description);
            }
            return sortedList;
        }
    }
}
